package com.roc.web.action.merinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerDetailForysBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.OperatorAuth;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.IUserService;
import com.roc.service.ServiceException;
import com.roc.service.operator.OperatorReceiveService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbMerDetailInfo")
public class MerDetailInfoForysbAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(MerDetailInfoForysbAction.class);
	private MerDtInfoForysbSearchCondition searchCondition;
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	IPagenitionService  pageService;
	@Autowired
	IExcelService excelService;
	private InputStream excelFile;
	private MerDetailForysBean detailForysBean;
	private Operators op;
	private String isAllowToReleLimit = "0"; //解限权限
	private Long detailId;
	private OperatorAuth operatorAuth;
	@Autowired
	private OperatorReceiveService operatorReceiveService;
	private String authIdList;
	private String allotOprNo;

	@Action(value = "init", results = { @Result(name = "success", location = "/pages/merinfo/ysbMerAuthDetailist.jsp"),
			@Result(name = "error", location = "/error.jsp")
	})	
	public String init() throws Exception{
		op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())){
			isAllowToReleLimit = "1";
		}
		getRequest().setAttribute("isAllowToReleLimit", isAllowToReleLimit);//解限权限
		return SUCCESS;
	}
	
	@Action(value = "ysbMerDetailists", 
			results = { @Result(name = "success", location = "/pages/merinfo/ysbMerAuthDetailist.jsp"),
			@Result(name = "error", location = "/error.jsp")
	})
	public String ysbMerDetailist() throws Exception{
		logger.info("========查询云商宝会员实名信息=======");
		op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {			
			if(searchCondition==null){
				searchCondition=(MerDtInfoForysbSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new MerDtInfoForysbSearchCondition();
				}
			}		
			int rows=pageService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pageService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);				
				if(searchRsList.size() > 0 && searchRsList != null){
					List<MerDetailForysBean> detList = handleYsbMerInfoDetail(searchRsList);
					searchRsList.clear();
					searchRsList.addAll(detList);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//当前条件统计总数
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			if(Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())||Role.RISK_CONTROL_OPERATORS.getCode().equals(op.getRoleType())||Role.SYSTEM.getCode().equals(op.getRoleType())){
				getRequest().setAttribute("isUpdate", "1");
			}else{
				getRequest().setAttribute("isUpdate", "0");
			}
			if(searchCondition.getStatus().equals("0")&&(Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())||Role.SYSTEM.getCode().equals(op.getRoleType()))){
				getRequest().setAttribute("isAllot", "1");
			}else{
				getRequest().setAttribute("isAllot", "0");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
		return SUCCESS;
	}
	
	public List<MerDetailForysBean> handleYsbMerInfoDetail(List<Object> objList) throws Exception{
		List<MerDetailForysBean> dList = new ArrayList<MerDetailForysBean>();
		Iterator<?> iterator=objList.iterator();
		while(iterator.hasNext()){
			Object[] obj = (Object[]) iterator.next();
			MerDetailForysBean mdf = new MerDetailForysBean();
			mdf.setMobile(Utils.dealMobile(Constance.Null2EmptyTrim(obj[0]))); //会员手机号
			mdf.setRealName(Utils.dealRealName(Constance.Null2EmptyTrim(obj[1]))); //真实姓名
			mdf.setPid(Utils.dealCardNo(Constance.Null2EmptyTrim(obj[2]))); //身份证号
			mdf.setCreateDate(Constance.Null2EmptyTrim(obj[3])); //创建时间
			mdf.setReceiveDate(Constance.Null2EmptyTrim(obj[4])); //领件时间
			mdf.setAuditDate(Constance.Null2EmptyTrim(obj[5])); //审核时间
			mdf.setOprNo(Constance.Null2EmptyTrim(obj[6])); //操作人
			mdf.setStatus(Constance.Null2EmptyTrim(obj[7])); //状态
			mdf.setDetailId(Constance.Null2EmptyTrim(obj[8])); //detail表id
			mdf.setReceiveId(Constance.Null2EmptyTrim(obj[9])); //receive表id
			mdf.setExt5(Constance.Null2EmptyTrim(obj[10])); //审核限制状态
			dList.add(mdf);
		}
		return dList;
	}
	
	/**
	 * 导出付临门云商宝会员信息
	 * @throws IOException 
	 */
	@Action(value = "exportYsbMerDetailist", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/merinfo/ysbMerAuthDetailist.jsp") })
	public String exportYsbMerDetailist() throws Exception {
		logger.info("导出付临门云商宝会员实名信息");
		op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())){
			if(searchCondition==null){
				searchCondition=(MerDtInfoForysbSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new MerDtInfoForysbSearchCondition();
				}
			}
			try {
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
				}
				List<MerDetailForysBean> dtList = handleYsbMerInfoDetail(searchRsList);
				SXSSFWorkbook work=excelService.exportYsbMerDetaiList(dtList, searchCondition.getMinDate(), searchCondition.getMaxDate());
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);
				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
			}catch (ServiceException e) {
				e.printStackTrace();
				logger.error(e.getMessage(),e);
				addActionError(e.getMessage());
			}
		}
			return SUCCESS;
		}
	
	public String getExcelName() {
		String excelName="付临门云商宝会员实名信息"+Constance.formateDate();
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		return  excelName;
	}
	
	/**
	 * 云商宝会员解限操作
	 * @return
	 */
	@Action(value="oprAuthReleaseLimit", results = {
			@Result(name = SUCCESS, type="chain", location = "ysbMerDetailists"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String oprAuthReleaseLimit(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			logger.info(op.getRealName()+"开始付临门会员实名认证解限操作,detail主键是："+detailId);
			String rtnStatus = operatorReceiveService.updateDetailForReleLimitInfo(op, detailId, operatorAuth);
			if(Role.RISK_CONTROL_LEAD.getCode().equals(op.getRoleType())){
				isAllowToReleLimit = "1";
			}
			getRequest().setAttribute("isAllowToReleLimit", isAllowToReleLimit);//解限权限
			if("1".equals(rtnStatus)){
				addActionMessage("解限成功！");
			}else if("2".equals(rtnStatus)){
				addActionMessage("已解限！");
			}else{
				addActionMessage("解限失败！");
			}
		} catch (Exception e) {
			logger.error("提交异常");
			logger.error(e.getMessage(),e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 风控主管分配实名信息给风控专员审核
	 */
	@Action(value="allotYsbOp")
	public void updateIdCardDate(){
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			Operators allotOp = operatorReceiveService.queryByAccountNo(allotOprNo);
			if(allotOp != null && allotOp.getId()>0 && allotOp.getStatus().equals("00")){
				List<String> list = operatorReceiveService.allotOperRece(op, authIdList,allotOp);
				json.put("msgCode", "0000");
				json.put("msgText", "分配成功");
				json.put("list", list);
			}else{
				json.put("msgCode", "0001");
				json.put("msgText", "分配账号不存在");
			}
			pw.write(json.toString());
		} catch (Exception e) {
			logger.error("分配异常");
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSBDETAIL_LIST_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_YSBDETAIL_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public MerDtInfoForysbSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerDtInfoForysbSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public MerDetailForysBean getDetailForysBean() {
		return detailForysBean;
	}

	public void setDetailForysBean(MerDetailForysBean detailForysBean) {
		this.detailForysBean = detailForysBean;
	}

	public Operators getOp() {
		return op;
	}

	public void setOp(Operators op) {
		this.op = op;
	}

	public String getIsAllowToReleLimit() {
		return isAllowToReleLimit;
	}

	public void setIsAllowToReleLimit(String isAllowToReleLimit) {
		this.isAllowToReleLimit = isAllowToReleLimit;
	}

	public Long getDetailId() {
		return detailId;
	}

	public void setDetailId(Long detailId) {
		this.detailId = detailId;
	}

	public OperatorAuth getOperatorAuth() {
		return operatorAuth;
	}

	public void setOperatorAuth(OperatorAuth operatorAuth) {
		this.operatorAuth = operatorAuth;
	}

	public String getAuthIdList() {
		return authIdList;
	}

	public void setAuthIdList(String authIdList) {
		this.authIdList = authIdList;
	}

	public String getAllotOprNo() {
		return allotOprNo;
	}

	public void setAllotOprNo(String allotOprNo) {
		this.allotOprNo = allotOprNo;
	}
}
